package com.ibr.ticketmanagement.app;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

import com.ibr.ticketmanagement.app.data.FEReport;
import com.ibr.ticketmanagement.app.util.Utility;

import java.util.Calendar;


public class FEReportActivity extends ActionBarActivity {

    private static View tempOptionView;
    private static boolean force24Hours = false;
    /**
     * Keep track of the fe report task to ensure we can cancel it if requested.
     */
    private FEReportTask mAuthTask = null;
    private FEReport feReport = null;
    private int ticketId;
    private int actionPlan_id;
    private int field_engineer;
    private View mProgressView;
    private View mLoginFormView;

    private boolean part_01_selected = false;
    private boolean part_02_selected = false;
    private boolean part_03_selected = false;
    private boolean part_04_selected = false;
    private boolean location_01_selected = false;
    private boolean location_02_selected = false;
    private boolean location_03_selected = false;
    private boolean location_04_selected = false;

    public static void setValueInView(String valueInView) {
        if (tempOptionView != null && tempOptionView instanceof EditText) {
            ((EditText) tempOptionView).setText(valueInView);
            tempOptionView = null;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fereport);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            ticketId = extras.getInt("ac_ticket_number", ActionPlanActivity.actionPlan.getTicketId());
            actionPlan_id = extras.getInt("ac_id", ActionPlanActivity.actionPlan.get_id());
        }
        field_engineer = Utility.getfeEngineerId(this);
        // TODO: initialise UI
        ((TextView) findViewById(R.id.ticket_id)).setText("Ticket #" + String.valueOf(ticketId));
        ((TextView) findViewById(R.id.action_plan_id)).setText("Action Plan #" + String.valueOf(actionPlan_id));

        LinearLayout ll = (LinearLayout) findViewById(R.id.location_part);

//        Spinner
        // dummy values

        ArrayAdapter<String> adapter_part_01 = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, Utility.getPart(this));
        ArrayAdapter<String> adapter_part_02 = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, Utility.getPart(this));
        ArrayAdapter<String> adapter_part_03 = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, Utility.getPart(this));
        ArrayAdapter<String> adapter_part_04 = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, Utility.getPart(this));

        final Spinner part_01 = (Spinner) findViewById(R.id.part_01);
        part_01.setAdapter(adapter_part_01);
        final Spinner part_02 = (Spinner) findViewById(R.id.part_02);
        part_02.setAdapter(adapter_part_02);
        final Spinner part_03 = (Spinner) findViewById(R.id.part_03);
        part_03.setAdapter(adapter_part_03);
        final Spinner part_04 = (Spinner) findViewById(R.id.part_04);
        part_04.setAdapter(adapter_part_04);


        ArrayAdapter<String> adapter_location_01 = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, Utility.getLocation(this));
        ArrayAdapter<String> adapter_location_02 = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, Utility.getLocation(this));
        ArrayAdapter<String> adapter_location_03 = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, Utility.getLocation(this));
        ArrayAdapter<String> adapter_location_04 = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, Utility.getLocation(this));
        final Spinner location_01 = (Spinner) findViewById(R.id.location_01);
        location_01.setAdapter(adapter_location_01);
        final Spinner location_02 = (Spinner) findViewById(R.id.location_02);
        location_02.setAdapter(adapter_location_02);
        final Spinner location_03 = (Spinner) findViewById(R.id.location_03);
        location_03.setAdapter(adapter_location_03);
        final Spinner location_04 = (Spinner) findViewById(R.id.location_04);
        location_04.setAdapter(adapter_location_04);

        location_01.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String selected = parent.getItemAtPosition(pos).toString();
                if ("Select Location".equals(selected)) {
                    location_01_selected = false;
                } else {
                    location_01_selected = true;
                }
                setQuantity(0);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        location_02.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String selected = parent.getItemAtPosition(pos).toString();
                if ("Select Location".equals(selected)) {
                    location_02_selected = false;
                } else {
                    location_02_selected = true;
                }
                setQuantity(1);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        location_03.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String selected = parent.getItemAtPosition(pos).toString();
                if ("Select Location".equals(selected)) {
                    location_03_selected = false;
                } else {
                    location_03_selected = true;
                }
                setQuantity(2);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        location_04.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String selected = parent.getItemAtPosition(pos).toString();
                if ("Select Location".equals(selected)) {
                    location_04_selected = false;
                } else {
                    location_04_selected = true;
                }
                setQuantity(3);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        part_01.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String selected = parent.getItemAtPosition(pos).toString();
                if ("Select Part".equals(selected)) {
                    part_01_selected = false;
                } else {
                    part_01_selected = true;
                }
                setQuantity(0);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        part_02.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String selected = parent.getItemAtPosition(pos).toString();
                if ("Select Part".equals(selected)) {
                    part_02_selected = false;
                } else {
                    part_02_selected = true;
                }
                setQuantity(1);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        part_03.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String selected = parent.getItemAtPosition(pos).toString();
                if ("Select Part".equals(selected)) {
                    part_03_selected = false;
                } else {
                    part_03_selected = true;
                }
                setQuantity(2);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        part_04.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String selected = parent.getItemAtPosition(pos).toString();
                if ("Select Part".equals(selected)) {
                    part_04_selected = false;
                } else {
                    part_04_selected = true;
                }
                setQuantity(3);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


        mLoginFormView = findViewById(R.id.fe_report_scrollView);
        mProgressView = findViewById(R.id.fe_report_progress);

    }

    private void setQuantity(int partLocationPosition) {
        switch (partLocationPosition) {
            case 0:
                if (location_01_selected && part_01_selected) {
                    Spinner location = (Spinner) findViewById(R.id.location_01);
                    Spinner part = (Spinner) findViewById(R.id.part_01);
                    Utility.getQuantity(this, part.getSelectedItem().toString(), location.getSelectedItem().toString(), (TextView) findViewById(R.id.totalQuantity_01));
                }
                break;
            case 1:
                if (location_02_selected && part_02_selected) {
                    Spinner location = (Spinner) findViewById(R.id.location_02);
                    Spinner part = (Spinner) findViewById(R.id.part_02);
                    Utility.getQuantity(this, part.getSelectedItem().toString(), location.getSelectedItem().toString(), (TextView) findViewById(R.id.totalQuantity_01));
                }
                break;
            case 2:
                if (location_03_selected && part_03_selected) {
                    Spinner location = (Spinner) findViewById(R.id.location_03);
                    Spinner part = (Spinner) findViewById(R.id.part_03);
                    Utility.getQuantity(this, part.getSelectedItem().toString(), location.getSelectedItem().toString(), (TextView) findViewById(R.id.totalQuantity_01));
                }
                break;
            case 3:
                if (location_04_selected && part_04_selected) {
                    Spinner location = (Spinner) findViewById(R.id.location_04);
                    Spinner part = (Spinner) findViewById(R.id.part_04);
                    Utility.getQuantity(this, part.getSelectedItem().toString(), location.getSelectedItem().toString(), (TextView) findViewById(R.id.totalQuantity_01));
                }
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.fereport, menu);
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void submitReport(View view) {
        showProgress(true);
        mAuthTask = new FEReportTask();
        mAuthTask.execute((Void) null);
    }

    public FEReport doValidateFeReport() {
        boolean isValid = true;
//        TextView fe_report_ticket_id = (TextView) findViewById(R.id.ticket_id);
//        TextView action_plan_id = (TextView) findViewById(R.id.action_plan_id);
        String field_engineer_uName = Utility.getUserName(this);
        if ("".equals(field_engineer_uName)) isValid = false;
        int field_engineer_id = Utility.getfeEngineerId(this);
        if ("".equals(field_engineer_id)) isValid = false;
        EditText work_window = (EditText) findViewById(R.id.work_window);
        String workWindow = work_window.getText().toString();
        if ("".equals(workWindow)) {
            isValid = false;
            work_window.setError("Work Window cannot be Empty.");
        }
        EditText time_started = (EditText) findViewById(R.id.time_started);
        String timeStart = time_started.getText().toString();
        if ("".equals(timeStart)) {
            isValid = false;
            time_started.setError("Start Time cannot be Empty.");
        }
        EditText time_finished = (EditText) findViewById(R.id.time_finished);
        String timeFinished = time_finished.getText().toString();
        if ("".equals(timeFinished)) {
            isValid = false;
            time_finished.setError("End Time cannot be Empty.");
        }
        EditText work_done = (EditText) findViewById(R.id.work_done);
        String work_done_value = work_done.getText().toString();
        if ("".equals(work_done_value)) {
            isValid = false;
            work_done.setError("Work Done cannot be Empty.");
        }
        CheckBox billable = (CheckBox) findViewById(R.id.billable);
        boolean billable_value = billable.isChecked();
        CheckBox closed = (CheckBox) findViewById(R.id.closed);
        boolean closed_value = closed.isChecked();
        EditText hours = (EditText) findViewById(R.id.hours);
        String hours_value = hours.getText().toString();
        if ("".equals(hours_value)) {
            isValid = false;
            hours.setError("Time Travel cannot be Empty.");
        }
        EditText miles = (EditText) findViewById(R.id.miles);
        String miles_value = miles.getText().toString();
        Spinner part_01 = (Spinner) findViewById(R.id.part_01);
        String part_01_value = part_01.getSelectedItem().toString();
        Spinner location_01 = (Spinner) findViewById(R.id.location_01);
        String location_01_value = location_01.getSelectedItem().toString();
        EditText numberPicker_01 = (EditText) findViewById(R.id.usedQuantity_01);
        int numberPicker_01_value = Integer.valueOf(numberPicker_01.getText().toString());
        EditText numberPicker_02 = (EditText) findViewById(R.id.usedQuantity_02);
        int numberPicker_02_value = Integer.valueOf(numberPicker_02.getText().toString());
        Spinner part_02 = (Spinner) findViewById(R.id.part_02);
        String part_02_value = part_02.getSelectedItem().toString();
        Spinner location_02 = (Spinner) findViewById(R.id.location_02);
        String location_02_value = location_02.getSelectedItem().toString();
        EditText numberPicker_03 = (EditText) findViewById(R.id.usedQuantity_03);
        int numberPicker_03_value = Integer.valueOf(numberPicker_03.getText().toString());
        Spinner part_03 = (Spinner) findViewById(R.id.part_03);
        String part_03_value = part_03.getSelectedItem().toString();
        Spinner location_03 = (Spinner) findViewById(R.id.location_03);
        String location_03_value = location_03.getSelectedItem().toString();
        EditText numberPicker_04 = (EditText) findViewById(R.id.usedQuantity_04);
        int numberPicker_04_value = Integer.valueOf(numberPicker_04.getText().toString());
        Spinner part_04 = (Spinner) findViewById(R.id.part_04);
        String part_04_value = part_04.getSelectedItem().toString();
        Spinner location_04 = (Spinner) findViewById(R.id.location_04);
        String location_04_value = location_04.getSelectedItem().toString();
        feReport = new FEReport(ticketId, actionPlan_id, field_engineer_id, workWindow, timeStart,
                timeFinished, work_done_value, billable_value, closed_value, hours_value,
                miles_value, numberPicker_01_value, part_01_value, location_01_value, numberPicker_02_value,
                part_02_value, location_02_value, numberPicker_03_value, part_03_value,
                location_03_value, numberPicker_04_value, part_04_value, location_04_value);
        if (!isValid) return null;
        return feReport;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    public void showProgress(final boolean show) {
        // The ViewPropertyAnimator APIs are not available, so simply show
        // and hide the relevant UI components.
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
    }

    public void setDate(View view) {
        int id = view.getId();
        tempOptionView = view;
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), id + "_datePicker");
    }

    public void setTime(View view) {
        int id = view.getId();
        if ("hours".equals(id)) {
            force24Hours = true;
        } else {
            force24Hours = false;
        }
        tempOptionView = view;
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getFragmentManager(), id + "_timePicker");
    }

    public static class DatePickerFragment extends DialogFragment
            implements DatePickerDialog.OnDateSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            setValueInView(year + "-" + (month + 1) + "-" + day);
        }
    }

    public static class TimePickerFragment extends DialogFragment
            implements TimePickerDialog.OnTimeSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current time as the default values for the picker
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            return new TimePickerDialog(getActivity(), this, hour, minute,
                    (force24Hours) ? true : DateFormat.is24HourFormat(getActivity()));
        }

        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            setValueInView(hourOfDay + ":" + minute + ":00");
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class FEReportTask extends AsyncTask<Void, Void, Boolean> {


        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                FEReport feReport = doValidateFeReport();
                if (feReport != null) {
                    // save in DB
                    Utility.saveFEReport(getApplicationContext(), feReport);
                    Utility.setActionPlanFEReportCreated(getApplicationContext(), actionPlan_id);
                    // Start the background service
                    Intent mServiceIntent = new Intent(getApplicationContext(), DatabaseService.class);
                    mServiceIntent.setAction("com.ibr.ticketmanagement.app.FEReportActivity");
                    // Starts the IntentService
                    startService(mServiceIntent);
                    return true;
                }
            } catch (Exception e) {
                Log.e("FEREPORTACTIVITY", "Could not create a FE REport", e.fillInStackTrace());
            }
            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                // Get the list of Action plans for execution.
                Intent i = new Intent(FEReportActivity.this, ActionPlanActivity.class);
                startActivity(i);
                showProgress(false);
                finish();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}
